/*
 *  Utilities.cpp
 *  GRE
 *
 *  Created by Kutlak Roman on 05/03/2012.
 *  Copyright 2012 Kutlak Roman. All rights reserved.
 *
 */

#include <cctype>

#include "Utilities.h"

namespace kutlak {
namespace roman {
namespace gre {

    using std::string;
    using std::vector;
    
    vector<string> SplitString(string str, const string& delim) 
    {
        vector<string> result;
        size_t pos = 0;
        size_t lastPos = 0;
        
        // to simplify the logic, add a delimiter at the end of the string
        str += delim;
        
        while ((pos = str.find(delim, pos)) != string::npos) 
        {
            string tmp = str.substr(lastPos, pos - lastPos);
            result.push_back(tmp);
            lastPos = ++pos;
        }
        
        return result;
    }
    
    string RemoveChars(string str, const string& chars) 
    {
        size_t poss = 0;
        while (string::npos != (poss = str.find_first_of(chars, poss)))
            str.replace(poss, 1, "");
        
        return str;
    }
    
    string Trim(string str, bool singleSpaces) 
    {
        if (str.length() < 2)
            return str;
        
        // delete initial spaces
        while (str.length() > 1 && isspace(str.front()))
            str.replace(0,1,"");
        
        if (singleSpaces) 
        {
            for (size_t i = 1; i < str.length(); ++i) 
            {
                if (isspace(str[i-1]) && isspace(str[i])) 
                {
                    str.replace(i-1, 2, " ");
                    --i;
                }
            }
        }
        
        while (str.length() > 1 && isspace(str.back()))
            str.pop_back();
        
        str.shrink_to_fit();
        return str;
    }
    
} // end namespace gre
}
}
